import React, { useEffect, useState } from 'react';
import { Application, ListView, DetailView } from '../core';
import { Window as WindowComponent } from '../components';
import { DataService } from '../services';
import { CommonViewController } from '../controllers';
import { initializeMockData } from '../mock';

export default function HomePage() {
  const [initialized, setInitialized] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    // Initialize mock data
    initializeMockData();

    // Initialize the application
    const app = Application.getInstance();
    const dataService = DataService.getInstance();
    
    // Using a mock API URL since we're using mock data
    const apiUrl = 'http://mock-api';
    
    dataService.initialize(apiUrl);
    
    app.initialize(apiUrl)
      .then(() => {
        console.log('Application initialized in index page, isInitialized =', app.isInitialized);
        setInitialized(true);
        setupDemoData(app);
      })
      .catch(err => {
        console.error('Failed to initialize application:', err);
        setError('Failed to initialize application. Please check the API URL and try again.');
      });
  }, []);

  // Function to set up demo data until the real backend is connected
  const setupDemoData = (app: Application) => {
    // We don't need to manually set up demo data now that we have the mock API and navigation
    console.log('Application initialized with mock data');
    
    // Just make sure we have a main window
    const mainWindow = app.windows[0] || app.createWindow('main', 'Mini-XAF Demo');
    app.setActiveWindow(mainWindow);
  };

  if (error) {
    return (
      <div className="error-container">
        <h2>Error</h2>
        <p>{error}</p>
        <button onClick={() => window.location.reload()}>Retry</button>
      </div>
    );
  }

  if (!initialized) {
    return (
      <div className="loading-container">
        <h2>Initializing Mini-XAF...</h2>
        <div className="loading-spinner"></div>
      </div>
    );
  }

  const app = Application.getInstance();
  const activeWindow = app.activeWindow;

  if (!activeWindow) {
    return <div>No active window available</div>;
  }

  return (
    <div className="mini-xaf-application">
      <WindowComponent model={activeWindow} />
    </div>
  );
}
